package cn.kgc.yigou.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class PhoneController {

    @RequestMapping("/sendCode")
    public Map<String, Object> login(String phone, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        int code = (int) ((Math.random() * 9 + 1) * 100000);
        session.setAttribute("code", code);
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4FgCsA6PRZZ3XScB8w9t", "VHMYGoytJ9TdT4SCcx8XFBQ05H5cwn");
        IAcsClient client = new DefaultAcsClient(profile);

        CommonRequest request = new CommonRequest();
        request.setMethod(MethodType.POST);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "codesendtion");
        request.putQueryParameter("TemplateCode", "SMS_182415416");
        request.putQueryParameter("TemplateParam", "{\"code\":" + code + "}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            System.out.println(response.getData());
            map.put("msg", "OK");
        } catch (com.aliyuncs.exceptions.ServerException e) {
            e.printStackTrace();
            map.put("msg", e.getMessage());
        } catch (ClientException e) {
            e.printStackTrace();
            map.put("msg", e.getMessage());
        }
        return map;
    }

    //验证登录
    @RequestMapping("/logins")
    @ResponseBody
    public Map<String, Object> login1(String code, HttpSession session) {
        Map<String, Object> map = new HashMap<>();
        String oldcode = session.getAttribute("code").toString();
        System.out.println(oldcode.equals(code));
        if (oldcode.equals(code)) {
            map.put("msg", "ok");
        } else {
            map.put("msg", "验证码错误");

        }
        return map;
    }

}


